package com.governtalk.backend.service.impl;

import com.governtalk.backend.dto.BrowseHistoryDto;
import com.governtalk.backend.entity.BrowseHistory;
import com.governtalk.backend.repository.BrowseHistoryRepository;
import com.governtalk.backend.service.BrowseHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional
public class BrowseHistoryServiceImpl implements BrowseHistoryService {
    
    @Autowired
    private BrowseHistoryRepository browseHistoryRepository;
    
    @Override
    public BrowseHistoryDto addBrowseHistory(BrowseHistoryDto browseHistoryDto) {
        // 检查是否已存在相同的浏览记录
        BrowseHistory existingHistory = browseHistoryRepository.findByUserIdAndContentTypeAndContentId(
            browseHistoryDto.getUserId(),
            browseHistoryDto.getContentType(),
            browseHistoryDto.getContentId()
        );
        
        if (existingHistory != null) {
            // 更新浏览时间
            existingHistory.setBrowseTime(LocalDateTime.now());
            browseHistoryRepository.save(existingHistory);
            return convertToDto(existingHistory);
        }
        
        BrowseHistory browseHistory = BrowseHistory.builder()
                .userId(browseHistoryDto.getUserId())
                .contentType(browseHistoryDto.getContentType())
                .contentId(browseHistoryDto.getContentId())
                .contentTitle(browseHistoryDto.getContentTitle())
                .contentDescription(browseHistoryDto.getContentDescription())
                .contentUrl(browseHistoryDto.getContentUrl())
                .browseTime(LocalDateTime.now())
                .build();
        
        BrowseHistory savedHistory = browseHistoryRepository.save(browseHistory);
        return convertToDto(savedHistory);
    }
    
    @Override
    public Page<BrowseHistoryDto> getUserBrowseHistory(Long userId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<BrowseHistory> histories = browseHistoryRepository.findByUserIdOrderByBrowseTimeDesc(userId, pageable);
        return histories.map(this::convertToDto);
    }
    
    @Override
    public Page<BrowseHistoryDto> getUserBrowseHistoryByType(Long userId, String contentType, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        BrowseHistory.ContentType type = BrowseHistory.ContentType.valueOf(contentType.toUpperCase());
        Page<BrowseHistory> histories = browseHistoryRepository.findByUserIdAndContentTypeOrderByBrowseTimeDesc(userId, type, pageable);
        return histories.map(this::convertToDto);
    }
    
    @Override
    public Page<BrowseHistoryDto> searchUserBrowseHistory(Long userId, String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<BrowseHistory> histories = browseHistoryRepository.findByUserIdAndKeyword(userId, keyword, pageable);
        return histories.map(this::convertToDto);
    }
    
    @Override
    public void deleteBrowseHistory(Long historyId) {
        browseHistoryRepository.deleteById(historyId);
    }
    
    @Override
    public void batchDeleteBrowseHistory(Long userId, Long[] historyIds) {
        for (Long historyId : historyIds) {
            browseHistoryRepository.deleteById(historyId);
        }
    }
    
    @Override
    public void clearUserBrowseHistory(Long userId) {
        browseHistoryRepository.deleteByUserId(userId);
    }
    
    @Override
    public void clearUserBrowseHistoryByType(Long userId, String contentType) {
        BrowseHistory.ContentType type = BrowseHistory.ContentType.valueOf(contentType.toUpperCase());
        browseHistoryRepository.deleteByUserIdAndContentType(userId, type);
    }
    
    private BrowseHistoryDto convertToDto(BrowseHistory browseHistory) {
        return BrowseHistoryDto.builder()
                .id(browseHistory.getId())
                .userId(browseHistory.getUserId())
                .contentType(browseHistory.getContentType())
                .contentId(browseHistory.getContentId())
                .contentTitle(browseHistory.getContentTitle())
                .contentDescription(browseHistory.getContentDescription())
                .contentUrl(browseHistory.getContentUrl())
                .browseTime(browseHistory.getBrowseTime())
                .createdAt(browseHistory.getCreatedAt())
                .build();
    }
}
